package com.yanyuan.snio.part;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;

/**
 * @author: yanyuan
 * @Date: 2021/3/29 11:21
 * @Description:
 * Pipe管道是2个线程之间的单向数据连接。
 * Pipe有一个source通道和一个sink通道
 * 数据被写到sink通道
 * 从source通道读取
 */
public class NioP12Pipe {

    public void send(Pipe pipe) throws IOException {
        //获取sink写入通道
        Pipe.SinkChannel sinkChannel = pipe.sink();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        buf.put("通道sink发送数据".getBytes(StandardCharsets.UTF_8));
        buf.flip();
        sinkChannel.write(buf);
        sinkChannel.close();
    }

    public void receive(Pipe pipe) throws IOException {
        //获取读取通道
        Pipe.SourceChannel sourceChannel = pipe.source();
        ByteBuffer buf = ByteBuffer.allocate(1024);
        int len = sourceChannel.read(buf);
        System.out.println("source接收数据：" + new String(buf.array(), 0, len));
        sourceChannel.close();
    }
}
